package com.lemonPiggy.UDForm.service.impl;

import com.lemonPiggy.UDForm.domain.MongoTest;
import com.lemonPiggy.UDForm.service.IMongoDBService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class IMongoDBServiceImpl implements IMongoDBService {
     @Autowired
     private MongoTemplate mongoTemplate;

    @Override
    public void save(MongoTest mongoTest) {
        mongoTemplate.save(mongoTest);
    }

    @Override
    public MongoTest findById(Integer id) {
        Query query = new Query(Criteria.where("_id").is(id));
        MongoTest one = mongoTemplate.findOne(query, MongoTest.class);
        return one;
    }

    @Override
    public void delete(Integer id) {
        Query query = new Query(Criteria.where("_id").is(id));
        mongoTemplate.remove(query,MongoTest.class);
    }

    @Override
    public void update(MongoTest mongoTest) {
        Query query = new Query(Criteria.where("_id").is(mongoTest.getId()));
        Update update = new Update();
        update.set("age",mongoTest.getAge());
        update.set("name",mongoTest.getName());
        mongoTemplate.updateFirst(query,update,MongoTest.class);
    }

    @Override
    public List<MongoTest> findAll() {
        List<MongoTest> test = mongoTemplate.findAll(MongoTest.class);
        return test;
    }


}
